import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { Photo } from '../types';
import { photoApi } from '../services/api';

export const usePhotoStore = defineStore('photos', () => {
  const photos = ref<Photo[]>([]);
  const error = ref<string>('');

  const loadPhotos = async () => {
    try {
      photos.value = await photoApi.getAllPhotos();
      error.value = '';
    } catch (err) {
      console.error('Failed to load photos:', err);
      error.value = '加载照片失败';
    }
  };

  const addPhoto = async (file: File, title: string, description: string) => {
    try {
      const newPhoto = await photoApi.uploadPhoto(file, title, description);
      photos.value.unshift(newPhoto);
      error.value = '';
    } catch (err) {
      console.error('Failed to add photo:', err);
      error.value = '上传照片失败';
      throw err;
    }
  };

  const deletePhoto = async (photoId: number) => {
    try {
      await photoApi.deletePhoto(photoId);
      const index = photos.value.findIndex(p => p.id === photoId);
      if (index !== -1) {
        photos.value.splice(index, 1);
      }
      error.value = '';
    } catch (err) {
      console.error('Failed to delete photo:', err);
      error.value = '删除照片失败';
      throw err;
    }
  };

  const clearError = () => {
    error.value = '';
  };

  return {
    photos,
    error,
    addPhoto,
    deletePhoto,
    clearError,
    loadPhotos
  };
});